package com.nbsaas.nbmall.shop.rest.resource;

import com.haoxuer.discover.data.utils.DateUtils;
import com.nbsaas.nbmall.shop.api.apis.ShopNotifierApi;
import com.nbsaas.nbmall.shop.api.domain.list.ShopNotifierList;
import com.nbsaas.nbmall.shop.api.domain.page.ShopNotifierPage;
import com.nbsaas.nbmall.shop.api.domain.request.*;
import com.nbsaas.nbmall.shop.api.domain.response.ShopNotifierResponse;
import com.nbsaas.nbmall.shop.data.dao.ShopNotifierDao;
import com.nbsaas.nbmall.shop.data.entity.ShopNotifier;
import com.nbsaas.nbmall.shop.rest.convert.ShopNotifierResponseConvert;
import com.nbsaas.nbmall.shop.rest.convert.ShopNotifierSimpleConvert;
import com.haoxuer.bigworld.tenant.data.entity.Tenant;
import com.haoxuer.discover.config.utils.ConverResourceUtils;
import com.haoxuer.discover.data.page.Filter;
import com.haoxuer.discover.data.page.Order;
import com.haoxuer.discover.data.page.Page;
import com.haoxuer.discover.data.page.Pageable;
import com.haoxuer.discover.data.utils.FilterUtils;
import com.nbsaas.nbmall.third.service.WxService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.haoxuer.bigworld.member.rest.conver.PageableConver;
import com.haoxuer.bigworld.tenant.util.TenantBeanUtils;
import com.haoxuer.bigworld.member.data.dao.TenantUserDao;
import com.nbsaas.nbmall.shop.data.dao.ShopDao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional
@Component
public class ShopNotifierResource implements ShopNotifierApi {

    @Autowired
    private ShopNotifierDao dataDao;

    @Autowired
    private TenantUserDao creatorDao;
    @Autowired
    private ShopDao shopDao;

    @Autowired
    private WxService wxService;


    @Override
    public ShopNotifierResponse create(ShopNotifierDataRequest request) {
        ShopNotifierResponse result = new ShopNotifierResponse();

        ShopNotifier bean = new ShopNotifier();
        bean.setTenant(Tenant.fromId(request.getTenant()));
        handleData(request, bean);
        dataDao.save(bean);
        result = new ShopNotifierResponseConvert().conver(bean);
        return result;
    }

    @Override
    public ShopNotifierResponse update(ShopNotifierDataRequest request) {
        ShopNotifierResponse result = new ShopNotifierResponse();
        if (request.getId() == null) {
            result.setCode(501);
            result.setMsg("无效id");
            return result;
        }
        ShopNotifier bean = dataDao.findById(request.getId());
        if (bean == null) {
            result.setCode(502);
            result.setMsg("无效id");
            return result;
        }
        handleData(request, bean);
        result = new ShopNotifierResponseConvert().conver(bean);
        return result;
    }

    private void handleData(ShopNotifierDataRequest request, ShopNotifier bean) {
       TenantBeanUtils.copyProperties(request,bean);
           if(request.getShop()!=null){
              bean.setShop(shopDao.findById(request.getShop()));
           }
           if(request.getCreator()!=null){
              bean.setCreator(creatorDao.findById(request.getCreator()));
           }

    }

    @Override
    public ShopNotifierResponse delete(ShopNotifierDataRequest request) {
        ShopNotifierResponse result = new ShopNotifierResponse();
        if (request.getId() == null) {
            result.setCode(501);
            result.setMsg("无效id");
            return result;
        }
        dataDao.deleteById(request.getTenant(),request.getId());
        return result;
    }

    @Override
    public ShopNotifierResponse view(ShopNotifierDataRequest request) {
        ShopNotifierResponse result=new ShopNotifierResponse();
        ShopNotifier bean = dataDao.findById(request.getTenant(), request.getId());
        if (bean==null){
            result.setCode(1000);
            result.setMsg("无效id");
            return result;
        }
        result=new ShopNotifierResponseConvert().conver(bean);
        return result;
    }
    @Override
    public ShopNotifierList list(ShopNotifierSearchRequest request) {
        ShopNotifierList result = new ShopNotifierList();

        List<Filter> filters = new ArrayList<>();
        filters.add(Filter.eq("tenant.id", request.getTenant()));
        filters.addAll(FilterUtils.getFilters(request));
        List<Order> orders = new ArrayList<>();
        if ("asc".equals(request.getSortMethod())){
           orders.add(Order.asc(""+request.getSortField()));
        }
        else if ("desc".equals(request.getSortMethod())){
           orders.add(Order.desc(""+request.getSortField()));
        }else{
           orders.add(Order.desc("id"));
        }
        List<ShopNotifier> organizations = dataDao.list(0, request.getSize(), filters, orders);

        ShopNotifierSimpleConvert convert=new ShopNotifierSimpleConvert();
        ConverResourceUtils.converList(result, organizations,convert);
        return result;
    }

    @Override
    public ShopNotifierResponse test(ShopNotifierDataRequest request) {
        ShopNotifierResponse result=new ShopNotifierResponse();
        ShopNotifier bean = dataDao.findById(request.getTenant(), request.getId());
        if (bean==null){
            result.setCode(1000);
            result.setMsg("无效id");
            return result;
        }

        WxMpService wxMpService = wxService.getWxMpService(request.getTenant());
        WxMpTemplateData data1=new WxMpTemplateData();
        data1.setName("first");
        data1.setValue("你收到一个新订单，请立即处理！");
        WxMpTemplateMessage msg=new WxMpTemplateMessage();
        msg.setTemplateId("uwQC9zfM8LmUIN2P92YCGCF4iI8vztoqT8W4Z9xnd-0");
        msg.setToUser(bean.getOpenId());
        msg.addData(data1);
        msg.addData(new WxMpTemplateData("keyword1",""));
        msg.addData(new WxMpTemplateData("keyword2","测试商品"));
        msg.addData(new WxMpTemplateData("keyword3","测试类型"));
        msg.addData(new WxMpTemplateData("keyword4",DateUtils.formatChines(new Date())));
        msg.addData(new WxMpTemplateData("keyword5","测试负责人"));
        msg.addData(new WxMpTemplateData("remark",""));
        WxMpTemplateMessage.MiniProgram min=new WxMpTemplateMessage.MiniProgram();
        min.setAppid("wx04ac1670e098dbf1");
        min.setPagePath("pages/channel/shop/index?id=685&visitType=visit");
        min.setUsePath(true);
        msg.setMiniProgram(min);
        //msg.setUrl("http://www.newbyte.ltd/");
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(msg);
        }catch (WxErrorException e){
            result.setCode(1000);
            result.setMsg(e.getError().getErrorMsg());
        }
        return result;
    }

    @Override
    public ShopNotifierPage search(ShopNotifierSearchRequest request) {
        ShopNotifierPage result=new ShopNotifierPage();
        Pageable pageable = new PageableConver().conver(request);
        pageable.getFilters().addAll(FilterUtils.getFilters(request));
        pageable.getFilters().add(Filter.eq("tenant.id", request.getTenant()));
        if ("asc".equals(request.getSortMethod())){
            pageable.getOrders().add(Order.asc(""+request.getSortField()));
        }
        else if ("desc".equals(request.getSortMethod())){
            pageable.getOrders().add(Order.desc(""+request.getSortField()));
        }else{
            pageable.getOrders().add(Order.desc("id"));
        }
        Page<ShopNotifier> page=dataDao.page(pageable);

        ShopNotifierSimpleConvert convert=new ShopNotifierSimpleConvert();
        ConverResourceUtils.converPage(result,page,convert);
        return result;
    }
}
